<?php

namespace Lims\DebtorBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Utils\SecurityBundle\CustomClass\SecurityFunctions;

class LegalEntityController extends Controller
{
    
    private $msg = null;
    
    public function listAction()
    {
        return $this->render('LimsDebtorBundle:LegalEntity:list.html.twig', array());
    }
    
    public function newAction()
    {
        $user = $this->checkIsLoggedIn();
        $aimagDuuregList = $this->getDoctrine()->getManager()->getRepository('LimsMainBundle:AimagDuureg')->findForList();
        $sumKhorooList = $this->getDoctrine()->getManager()->getRepository('LimsMainBundle:SumKhoroo')->findForList();
        $legalEntityTypeList = $this->getDoctrine()->getManager()->getRepository('LimsMainBundle:LegalEntityType')->findForList();
        
        return $this->render('LimsDebtorBundle:LegalEntity:new.html.twig', array(
            'aimagDuuregList' => $aimagDuuregList, 
            'sumKhorooList' => $sumKhorooList,
            'legalEntityTypeList' => $legalEntityTypeList
                
        ));
    }
    
    public function editAction()
    {
        return $this->render('LimsDebtorBundle:LegalEntity:edit.html.twig', array());
    }
    
    public function createAction(Request $request)
    {
        $user = $this->checkIsLoggedIn();
        
        $legalEntityData = $this->checkLegalEntity();
        
        if($this->msg != null)
        {
            $this->get('session')->getFlashBag()->add('error', $this->msg);
            return new RedirectResponse($this->getRequest()->headers->get('referer'));
        }
        
        try{
            
            // SAVE LEGAL ENTITY
            $legalEntityObject = $this->getDoctrine()->getManager()->getRepository('LimsMainBundle:LegalEntity')->saveLegalEntity($legalEntityData, $this->container->get('security.context')->getToken()->getUser()->getId());
            
            //SAVE DEBTOR
            // SAVE DEBTOR
            $debtor = $this->getDoctrine()->getManager()->getRepository('LimsMainBundle:Debtor')->saveCitizenDebtor($this->container->get('security.context')->getToken()->getUser()->getId(), null, $legalEntityObject);
            
            // SAVE OWNER CITIZEN
            $citizenDataArray = $this->getOwnerDataFromLegalEntity($legalEntityData);
            foreach ($citizenDataArray AS $citizenData)
            {
                $ownerCitizenObject = $this->getDoctrine()->getManager()->getRepository('LimsMainBundle:Citizen')->saveCitizen($citizenData, $this->container->get('security.context')->getToken()->getUser()->getId());
                $legalEntityOwnerMapObject = $this->getDoctrine()->getManager()->getRepository('LimsMainBundle:LegalEntityOwnerMap')->saveLegalEntityOwnerMap($legalEntityObject, $ownerCitizenObject, $this->container->get('security.context')->getToken()->getUser()->getId());
            }
            
        }  catch (\Exception $e)
        {
            $this->get('session')->getFlashBag()->add('error', 'Үйлдэл амжилтгүй боллоо');
            return new RedirectResponse($this->generateUrl('lims_debtor_list'));
        }
        
        
        
        return new RedirectResponse($this->generateUrl('lims_credit_new', array('registerNumber' => $legalEntityObject->getRegisterNumber())));
    }
    
    private function checkLegalEntity()
    {
        $legalEntityData = array();
        /**
         * REGISTER NUMBER шалгуур
         */
        if(!isset($_POST['lentity_register_number']))
        {
            $this->msg .= $this->container->getParameter('ERROR_MSG_LEGAL_ENTITY_2');
        }else if(strlen($_POST['lentity_register_number']) == 0)
        {
            $this->msg .= $this->container->getParameter('ERROR_MSG_LEGAL_ENTITY_2');   
        }else{
            $legalEntityData['lentity_register_number'] = SecurityFunctions::clear($_POST['lentity_register_number']);
        }
        
        $legalEntityData = $_POST;
        return $legalEntityData;
    }
    
    private function getOwnerDataFromLegalEntity($legalEntityData)
    {
        $ownerData = array();
        
        $count = count($legalEntityData['owner_family_name']);
        if($count > 0)
        {
            for ($i = 0; $i < $count; $i++)
            {
                $ownerData[$i]['citizen_family_name'] = $legalEntityData['owner_family_name'][$i];
                $ownerData[$i]['citizen_last_name'] = $legalEntityData['owner_last_name'][$i];
                $ownerData[$i]['citizen_first_name'] = $legalEntityData['owner_first_name'][$i];
                $ownerData[$i]['citizen_register_number'] = $legalEntityData['owner_register_number'][$i];
                $ownerData[$i]['citizen_address_1'] = $legalEntityData['owner_address_1'][$i];
                $ownerData[$i]['citizen_address_2'] = $legalEntityData['owner_address_2'][$i];
                $ownerData[$i]['citizen_address_full'] = $legalEntityData['owner_address_full'][$i];
                $ownerData[$i]['citizen_phone'] = $legalEntityData['owner_phone'][$i];
                $ownerData[$i]['citizen_email'] = $legalEntityData['owner_email'][$i];                
            }
        }
        
        return $ownerData;
        
    }
    
    private function checkIsLoggedIn()
    {
		if('anon.' == $this->container->get('security.context')->getToken()->getUser())
		{
			header("Location: /exit/");
		}
		
        if($this->container->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY') === FALSE)
        {
            header("Location: /exit/");
        }else{
            return $this->container->get('security.context')->getToken()->getUser();
        }
    }
    
}
